<?php


namespace common\service;


use common\exception\LogicException;
use common\model\EntityModel;
use common\model\ModuleModel;
use common\model\StatusModel;
use common\model\StepCategoryModel;
use common\model\UserModel;
use support\EntityTaskFilterParser;
use support\ErrorCode;
use support\SingletonTrait;
use think\Exception;
use think\module\Module;

class AssetService
{

    /**
     * @var EntityModel
     */
    private $entityModel;

    // 引入实体任务多模块筛选条件解析类
    use EntityTaskFilterParser;

    // 单例工具类
    use SingletonTrait;

    public function __construct()
    {
        $this->entityModel = model(EntityModel::class);
    }

    /**
     * 合并模块实体任务树
     * @param $params
     * @param int $currentTenantId
     * @param string $moduleCode
     * @return array
     */
    public function getMergeModuleEntityTaskTree($params, int $currentTenantId, string $moduleCode)
    {
        $extraEntityFilter = $this->parseMultipleEntityTaskFilter($params['filter']);
        $episodeId = $params['filter']['episode_id'] ?? 0;
        $projectId = $params['filter']['project_id'];

        $page = $params['page'] ?? [1, C("database.database_max_select_rows")];
        $order = $params['order'] ?? ['entity.name', 'entity.id'];
        $res = [
            'total' => 0,
            'rows' => []
        ];
        $moduleCodes = [$moduleCode];
        $optionService = OptionsService::getInstance();
        $mergeModuleConfig = $optionService->getOptionsData('merge_module_config');

        if (!empty($mergeModuleConfig[$moduleCode])) {
            $moduleCodes = explode(',', $mergeModuleConfig[$moduleCode]);
        }
        if (!empty($moduleSearchList)) {
            $moduleCodes = array_filter($moduleCodes, function ($item) use ($moduleSearchList) {
                return in_array($item, $moduleSearchList);
            });
        }
        if (empty($moduleCodes)) {
            return $res;
        }
        $moduleIds = [];
        foreach ($moduleCodes as $tmpModuleCode) {
            $moduleIds[] = Module::$moduleDictData['module_index_by_code'][$tmpModuleCode]['id'];
        }
        $entityFilter = [
            'entity.tenant_id' => $currentTenantId,
            'entity.project_id' => $projectId,
            'entity.module_id' => ['IN', implode(',', $moduleIds)],
            'entity.is_generate' => 'yes',
            'task.step_type' => 'step',
        ];
        if ($episodeId > 0) {
            $episode = model(EntityModel::class)
                ->field("id,code")
                ->find($episodeId);
            if (empty($episode)) {
                throw new LogicException('episode not found', ErrorCode::MISSING_EPISODE);
            }
            $entityFilter['initial_episode_code'] = $episode['code'];
        }
        if (!empty($extraEntityFilter)) {
            $entityFilter = array_merge($entityFilter, $extraEntityFilter);
        }

        // 计划只有一条 合并了其他实体模块
        /**
         * 资产 => (资产,概念,关卡)
         * 镜头 => (镜头,分镜,序列)
         */
        $entityQueryFields = [
            'entity.id', 'entity.name', 'entity.code', 'entity.duration', 'entity.showings_number', 'entity.initial_episode_code',
            'entity.module_id', 'entity.entity_id', 'entity.entity_module_id', 'entity.json', 'entity.is_assignee', 'entity.initial_episode_code',
            'entity.plan_start_time', 'entity.plan_end_time',
            'task.id', 'task.name', 'task.code', 'task.entity_id', 'task.step_category_id', 'task.step_id', 'task.step_type', 'task.pre_task_id',
            'task.executor_tenant_id', 'task.assignee_producer', 'task.assignee', 'task.tenant_id', 'task.executor', 'task.executor_confirmed',
            'task.assignee_at', 'task.is_assignee', 'task.assign_status', 'task.task_status', 'task.plan_start_time', 'task.plan_end_time',
            'task.start_time', 'task.end_time', 'task.department_id',
        ];
        $res['total'] = $this->entityModel
            ->join('task ON task.entity_id = entity.id')
            ->join('module ON module.id = task.entity_module_id')
            ->where($entityFilter)
            ->count();

        if ($res['total'] === 0) {
            return $res;
        }
        $bindStepCategory = model(StepCategoryModel::class)->where([
            'entity_id' => ['IN', implode(',', $moduleIds)],
            'parent_id' => 0,
        ])->select();
        $bindStepCategory = array_column($bindStepCategory, null, 'entity_id');
        // 先查询所有的实体 然后处理任务数据
        $taskQueryList = $this->entityModel
            ->join('task ON task.entity_id = entity.id')
            ->join('module ON module.id = task.entity_module_id')
            //            ->join('step_category on step_category.id = task.step_category_id', 'LEFT')
            ->where($entityFilter)
            ->page($page[0], $page[1])
            ->field(implode(',', build_complex_query_fields($entityQueryFields, '__')))
            ->order($order)
            ->select();

        $entityList = [];
        $taskList = [];
        $entityIdList = [];
        $insideSupplierUserId = [];
        $outsideSupplierTenantId = [];
        $taskStatusIdList = [];
        $departmentIdMap = [];
        $episodeCodeList = [];
        foreach ($taskQueryList as $task) {
            $task = separate_complex_query_data($task, '__');
            if (!in_array($task['entity']['id'], $entityIdList)) {
                $entityList[] = $task['entity'];
                $entityIdList[] = $task['entity']['id'];
            }
            if (!empty($task['entity']['initial_episode_code'])) {
                $episodeCodeList[$task['entity']['initial_episode_code']] = $task['entity']['initial_episode_code'];
            }
            $task['task']['step_category_index'] = $task['task']['step_category']['index'] ?? 0;
            $task['task']['row_type'] = 'task';
            $taskList[] = $task['task'];
            if ($task['task']['assignee'] > 0 && !in_array($task['task']['assignee'], $insideSupplierUserId)) {
                $insideSupplierUserId[] = $task['task']['assignee'];
            }
            if ($task['task']['executor_tenant_id'] > 0 && $task['task']['executor_tenant_id'] != $currentTenantId && !in_array($task['task']['executor_tenant_id'], $outsideSupplierTenantId)) {
                $outsideSupplierTenantId[] = $task['task']['executor_tenant_id'];
            }
            if ($task['task']['task_status'] > 0 && !in_array($task['task']['task_status'], $taskStatusIdList)) {
                $taskStatusIdList[] = $task['task']['task_status'];
            }
            if ($task['task']['department_id'] > 0) {
                $departmentIdMap[$task['task']['department_id']] = $task['task']['department_id'];
            }
        }
        unset($entityIdList, $taskQueryList);
        $taskList = array_group_by($taskList, 'entity_id');
        // 供应商信息
        $taskService = TaskService::getInstance();
        $supplierRes = $taskService->queryTaskSupplierInfo($currentTenantId, $insideSupplierUserId, $outsideSupplierTenantId, $departmentIdMap);

        // 集查询
        $episodeList = [];
        if (!empty($episodeCodeList)) {
            $episodeList = EpisodeService::getInstance()->selectEpisodeMap(['project_id' => $projectId, 'code' => ['IN', array_keys($episodeCodeList)]]);
        }
        // 查询状态
        $statusList = [];
        if (count($taskStatusIdList)) {
            $statusList = model(StatusModel::class)->where(['id' => ['IN', implode(',', $taskStatusIdList)]])->select();
            $statusList = array_column($statusList, null, 'id');
        }
        $entityGroupedData = [];
        $notStartedStatusList = StatusService::getInstance()->getNotStartedStatus();
        $notStartedStatusIdList = array_column($notStartedStatusList, 'id');
        foreach ($entityList as &$entity) {

            $entityId = $entity['id'];
            $entity['row_type'] = 'entity';
            $entity['step_category'] = $bindStepCategory[$entity['module_id']] ?? null;
            $entity['module'] = Module::$moduleDictData['module_index_by_id'][$entity['module_id']] ?? null;
            $configArray = json_decode($entity['json'], true);
            $entity = array_merge($entity, $configArray);
            $entity['can_withdraw_task_ids'] = [];
            $entity['executor'] = '';
            unset($entity['json']);
            if (!array_key_exists($entity['name'], $entityGroupedData)) {
                $entityGroupedData[$entity['name']] = array_merge($entity, ['children' => [], 'episode' => $episodeList[$entity['initial_episode_code']] ?? null, 'wait_assign_count' => 0, 'task_ids' => []]);
            }
            $childrenTasks = $taskList[$entityId] ?? [];
            foreach ($childrenTasks as &$childrenTask) {
                $childrenTask['episode_id'] = !empty($entityGroupedData[$entity['name']]['episode']) ? $entityGroupedData[$entity['name']]['episode']['id'] : 0;
                $childrenTask['is_outside'] = false;
                if ($childrenTask['executor_tenant_id'] > 0 && $childrenTask['executor_tenant_id'] != $currentTenantId) {
                    $childrenTask['assignee_user'] = $supplierRes['outside'][$childrenTask['executor_tenant_id']] ?? null;
                    $childrenTask['is_outside'] = true;
                } else if ($childrenTask['department_id'] > 0) {
                    $childrenTask['assignee_user'] = $supplierRes['department'][$childrenTask['department_id']] ?? null;
                    if (in_array($childrenTask['task_status'], $notStartedStatusIdList)) {
                        $entityGroupedData[$entity['name']]['can_withdraw_task_ids'][] = $childrenTask['id'];
                    }
                }
                if ($childrenTask['assign_status'] === 'default' || $childrenTask['assign_status'] === 'rejected') {
                    $entityGroupedData[$entity['name']]['wait_assign_count'] += 1;
                }
                if (!empty($childrenTask['assignee_user'])) {
                    $executorTaskName = $childrenTask['name'] . "({$childrenTask['assignee_user']['name']})";
                    if (strpos($entityGroupedData[$entity['name']]['executor'], $executorTaskName) === false) { //去除重复
                        $entityGroupedData[$entity['name']]['executor'] .= empty($entityGroupedData[$entity['name']]['executor']) ? $executorTaskName : ',' . $executorTaskName;
                    }
                }
                $childrenTask['supplier_info'] = null;
                $childrenTask['department_info'] = null;
                $childrenTask['task_status'] = $statusList[$childrenTask['task_status']] ?? null;
                $childrenTask['entity_name'] = $entity['name'];
                $entityGroupedData[$entity['name']]['children'][] = $childrenTask;
                $entityGroupedData[$entity['name']]['task_ids'][] = $childrenTask['id'];
            }
        }
        $res['rows'] = array_values($entityGroupedData);
        return $res;
    }

    /**
     * 分配任务弹出任务树查询
     * @param $taskIdList
     * @param $stepCategoryId
     * @param $episodeId
     * @return array
     * @throws Exception
     */
    public function getAssignPopTaskTree($taskIdList, $stepCategoryId, $episodeId)
    {
        $plan = PlanService::getInstance()->getPlan(['type' => 'step_category', 'entity_id' => $episodeId, 'step_category_id' => $stepCategoryId]);
        if (empty($plan)) {
            $plan = PlanService::getInstance()->getPlan(['type' => 'episode', 'entity_id' => $episodeId]);
            if (empty($plan)) {
                throw new LogicException('episode plan not found', ErrorCode::PLAN_NOT_FOUND);
            }
        }
        $entityFilter = [
            'entity.is_generate' => 'yes',
            'task.step_type' => 'step',
            'task.id' => ['IN', implode(',', $taskIdList)]
        ];
        // 计划只有一条 合并了其他实体模块
        /**
         * 资产 => (资产,概念,关卡)
         * 镜头 => (镜头,分镜,序列)
         */
        $entityQueryFields = [
            'entity.id', 'entity.name', 'entity.code', 'entity.duration', 'entity.showings_number', 'entity.initial_episode_code',
            'entity.module_id', 'entity.entity_id', 'entity.entity_module_id', 'entity.json', 'entity.is_assignee', 'entity.project_id',
            'entity.initial_episode_code', 'entity.plan_start_time', 'entity.plan_end_time',
            'task.id', 'task.name', 'task.code', 'task.entity_id', 'task.step_category_id', 'task.step_id', 'task.tenant_id',
            'task.step_type', 'task.pre_task_id', 'task.executor_tenant_id', 'task.assignee_producer', 'task.assignee', 'task.executor',
            'task.executor_confirmed', 'task.assignee_at', 'task.is_assignee', 'task.assign_status', 'task.task_status', 'task.plan_start_time', 'task.plan_end_time', 'task.department_id',
        ];
        // 先查询所有的实体 然后处理任务数据
        $taskQueryList = $this->entityModel
            ->join('module on module.id = entity.module_id')
            ->join('task ON task.entity_id = entity.id')
            ->join('step_category on step_category.id = task.step_category_id', 'LEFT')
            ->where($entityFilter)
            ->field(implode(',', build_complex_query_fields($entityQueryFields, '__')))
            ->select();

        $entityList = [];
        $taskList = [];
        $entityIdList = [];
        $insideSupplierUserId = [];
        $outsideSupplierTenantId = [];
        $departmentIdMap = [];
        $episodeCode = '';
        $projectId = 0;
        $tenantId = 0;
        foreach ($taskQueryList as $task) {
            $task = separate_complex_query_data($task, '__');
            if (!in_array($task['entity']['id'], $entityIdList)) {
                $entityList[] = $task['entity'];
                $entityIdList[] = $task['entity']['id'];
            }
            $task['task']['row_type'] = 'task';
            if (empty($episodeCode)) {
                $episodeCode = $task['entity']['initial_episode_code'];
            }
            if (empty($projectId)) {
                $projectId = $task['entity']['project_id'];
            }
            if (empty($tenantId)) {
                $tenantId = $task['task']['tenant_id'];
            }
            $taskList[] = $task['task'];
            if ($task['task']['assignee'] > 0 && !in_array($task['task']['assignee'], $insideSupplierUserId)) {
                $insideSupplierUserId[] = $task['task']['assignee'];
            }
            if ($task['task']['executor_tenant_id'] > 0 && $task['task']['executor_tenant_id'] != $task['task']['tenant_id'] && !in_array($task['task']['executor_tenant_id'], $outsideSupplierTenantId)) {
                $outsideSupplierTenantId[] = $task['task']['executor_tenant_id'];
            }
            if ($task['task']['department_id'] > 0) {
                $departmentIdMap[$task['task']['department_id']] = $task['task']['department_id'];
            }
        }
        unset($entityIdList, $taskQueryList);
        $taskList = array_group_by($taskList, 'entity_id');

        // 供应商信息
        $taskService = TaskService::getInstance();
        $supplierRes = $taskService->queryTaskSupplierInfo($tenantId, $insideSupplierUserId, $outsideSupplierTenantId, $departmentIdMap);

        $entityGroupedData = [];
        foreach ($entityList as &$entity) {
            $entityId = $entity['id'];
            $entity['row_type'] = 'entity';
            $entity['module'] = Module::$moduleDictData['module_index_by_id'][$entity['module_id']] ?? null;
            $configArray = json_decode($entity['json'], true);
            foreach ($configArray as $fieldKey => $fieldValue) {
                $entity[str_replace_once(Module::$moduleDictData['module_index_by_id'][$entity['module_id']]['code'] . '_', '', $fieldKey)] = $fieldValue;
            }
            unset($entity['json']);
            if (!array_key_exists($entity['name'], $entityGroupedData)) {
                $entityGroupedData[$entity['name']] = array_merge($entity, ['children' => []]);
            }
            $childrenTasks = $taskList[$entityId] ?? [];
            foreach ($childrenTasks as &$childrenTask) {
                $childrenTask['is_outside'] = false;
                if ($childrenTask['executor_tenant_id'] > 0 && $childrenTask['executor_tenant_id'] != $childrenTask['tenant_id']) {
                    $childrenTask['is_outside'] = true;
                    $childrenTask['assignee_user'] = $supplierRes['outside'][$childrenTask['executor_tenant_id']] ?? null;
                } else if ($childrenTask['department_id'] > 0) {
                    $childrenTask['assignee_user'] = $supplierRes['department'][$childrenTask['department_id']] ?? null;
                }

                $childrenTask['entity_name'] = $entity['name'];
                $childrenTask['task_ids'] = [$childrenTask['id']];
                $entityGroupedData[$entity['name']]['children'][] = $childrenTask;
            }
        }
        return ['plan' => $plan, 'rows' => array_values($entityGroupedData)];
    }

    /**
     * 资产搜索推荐
     * @param array $filter 筛选条件
     * @param int $limit 查询条数限制
     * @return array
     * @throws \Exception
     */
    public function searchRecommend(array $filter, int $limit = 10)
    {
        $filter = $this->parseMultipleEntityTaskFilter($filter);
        // 追加关卡和资产的搜索限制
        $filter['entity.module_id'] = ["IN", [module_by_code('asset')['id'], module_by_code('level')['id']]];
        $rows = $this->entityModel
            ->join('module on module.id = entity.module_id')
            ->where($filter)
            ->field('entity.id,entity.name,entity.code,entity.json,module.code AS module_code')
            ->limit($limit)
            ->select();

        return array_map(function ($item) {
            $itemJsonFields = json_decode($item['json'] ?? '{}', true);
            unset($item['json']);
            foreach ($itemJsonFields as $k => $v) {
                $item[str_replace_once($item['module_code'] . "_", '', $k)] = $v;
            }
            return $item;
        }, $rows);
    }

    /**
     * 合并模块实体任务列表
     * @param $params
     * @param int $currentTenantId
     * @param int $userId
     * @return array
     * @throws Exception
     */
    public function getGenerateEntityTaskList($params, int $currentTenantId, int $userId)
    {
        $filter = $params['filter'] ?? [];

        if (empty($filter['module_code'])) {
            $moduleCodes = OptionsService::getInstance()->getOptionsData('merge_module_config');
            $moduleCodes = array_values($moduleCodes);
            $moduleCodes = join(',', $moduleCodes);
            $filter['module_code'] = ["IN", $moduleCodes];
        }

        $extraEntityFilter = $this->parseMultipleEntityTaskFilter($filter);
        $episodeId = $params['filter']['episode_id'] ?? 0;
        $projectId = $params['filter']['project_id'] ?? null;

        $statusList = array_column(model(StatusModel::class)->field('id,code')->select(), 'id', 'code');
        $page = $params['page'] ?? [1, C("default_page_total")];
        $order = $params['order'] ?? ['task.entity_id'];
        $entityFilter = [
            'entity.tenant_id' => $currentTenantId,
            'entity.is_generate' => 'yes',
            'task.step_type' => 'step',
            "JSON_UNQUOTE(JSON_EXTRACT(entity.json,CONCAT( '$.',module.code,'_status')))" => ['NEQ', $statusList['closed']] // 过滤废除的清单
        ];

        if (!isset($projectId)) {
            $projectList = ProjectService::getInstance()->getUserProjectList($userId, ['param' => ['project_status' => 'inprogress']]);
            $projectIds = array_column(array_column($projectList['rows'], 'project'), 'id');
            if (!empty($projectIds)) {
                $projectId = ["IN", $projectIds];
            }
        }

        if (!empty($projectId)) {
            $entityFilter['entity.project_id'] = $projectId;
        }


        if ($episodeId > 0) {
            $episode = model(EntityModel::class)->field("id,code")->find($episodeId);
            if (empty($episode)) {
                throw new LogicException('episode not found', ErrorCode::MISSING_EPISODE);
            }
            $entityFilter['initial_episode_code'] = $episode['code'];
        }
        if (!empty($extraEntityFilter)) {
            $entityFilter = array_merge($entityFilter, $extraEntityFilter);
        }

        // 计划只有一条 合并了其他实体模块
        /**
         * 资产 => (资产,概念,关卡)
         * 镜头 => (镜头,分镜,序列)
         */
        $entityQueryFields = [
            'entity.id', 'entity.name', 'entity.code', 'entity.duration', 'entity.showings_number', 'entity.initial_episode_code',
            'entity.module_id', 'entity.entity_id', 'entity.entity_module_id', 'entity.json', 'entity.is_assignee', 'entity.initial_episode_code',
            'entity.plan_start_time', 'entity.plan_end_time',
            'task.id', 'task.name', 'task.code', 'task.entity_id', 'task.step_category_id', 'task.step_id', 'task.step_type', 'task.pre_task_id',
            'task.executor_tenant_id', 'task.assignee_producer', 'task.assignee', 'task.tenant_id', 'task.executor', 'task.executor_confirmed',
            'task.assignee_at', 'task.is_assignee', 'task.assign_status', 'task.task_status', 'task.plan_start_time', 'task.plan_end_time',
            'task.start_time', 'task.end_time', 'task.department_id', 'module.code', 'task.json'
        ];

        // 先查询所有的实体 然后处理任务数据
        $taskQueryList = model(ModuleModel::class)->join('`entity` on module.id = entity.module_id')->join('task ON task.entity_id = entity.id')
            ->where($entityFilter)->page($page[0], $page[1])->field(implode(',', build_complex_query_fields($entityQueryFields, '__')))
            ->order($order)
            ->select();


        // 查询所有用户信息
        $userDict = [];
        $executorIds = [];
        foreach ($taskQueryList as $value) {
            if ($value['task__is_assignee'] == 'yes') {
                $executorIds[] = $value['task__executor'];
            }
        }
        if (!empty($executorIds)) {
            $userData = model(UserModel::class)->field('id,name,phone,union_id,avatar')->where(['id' => ['IN', join(',', $executorIds)]])->select();
            $userDict = array_column($userData, null, 'id');
        }
        $insideSupplierUserId = [];
        $outsideSupplierTenantId = [];
        $taskStatusIdList = [];
        $departmentIdMap = [];
        $episodeCodeList = [];
        $entityParentIds = [];
        foreach ($taskQueryList as $index => $task) {
            $task = separate_complex_query_data($task, '__');
            $taskQueryList[$index] = $task;
            //集
            if (!empty($task['entity']['initial_episode_code'])) {
                $episodeCodeList[$task['entity']['initial_episode_code']] = $task['entity']['initial_episode_code'];
            }
            //分配人
            if ($task['task']['assignee'] > 0 && !in_array($task['task']['assignee'], $insideSupplierUserId)) {
                $insideSupplierUserId[] = $task['task']['assignee'];
            }
            //外包商
            if ($task['task']['executor_tenant_id'] > 0 && $task['task']['executor_tenant_id'] != $currentTenantId && !in_array($task['task']['executor_tenant_id'], $outsideSupplierTenantId)) {
                $outsideSupplierTenantId[] = $task['task']['executor_tenant_id'];
            }
            if ($task['task']['task_status'] > 0 && !in_array($task['task']['task_status'], $taskStatusIdList)) {
                $taskStatusIdList[] = $task['task']['task_status'];
            }
            if ($task['task']['department_id'] > 0) {
                $departmentIdMap[$task['task']['department_id']] = $task['task']['department_id'];
            }

            if (!in_array($task['entity']['entity_id'], $entityParentIds) && $task['entity']['entity_id'] > 0) {
                $entityParentIds[] = $task['entity']['entity_id'];
            }
        }

        $entityParentList = [];
        if (!empty($entityParentIds)) {
            $entityParentList = model(EntityModel::class)->join('module on entity.module_id = module.id')
                ->where(['entity.id' => ['IN', $entityParentIds]])->field('entity.id,entity.name,entity.code,module.code as module_code')->select();
            $entityParentList = array_column($entityParentList, null, 'id');
        }

        // 供应商信息
        $supplierRes = TaskService::getInstance()->queryTaskSupplierInfo($currentTenantId, $insideSupplierUserId, $outsideSupplierTenantId, $departmentIdMap);
        // 集查询
        $episodeList = [];
        if (!empty($episodeCodeList)) {
            $episodeList = EpisodeService::getInstance()->selectEpisodeMap(['project_id' => $projectId, 'code' => ['IN', array_keys($episodeCodeList)]]);
        }
        // 查询状态
        $statusList = [];
        if (!empty($taskStatusIdList)) {
            $statusList = model(StatusModel::class)->where(['id' => ['IN', implode(',', $taskStatusIdList)]])->select();
            $statusList = array_column($statusList, null, 'id');
        }

        $res = [];
        foreach ($taskQueryList as $taskItem) {
            $isDismantleTask = null;
            $dismantleName = '';
            $entity = $taskItem['entity'];
            $task = $taskItem['task'];
            $configArray = json_decode($entity['json'], true);
            $entityJson = [];
            foreach ($configArray as $fieldKey => $configArrayItem) {
                $entityJson[str_replace_once($taskItem['module']['code'] . '_', '', $fieldKey)] = $configArrayItem;
            }

            if (isset($entityParentList[$entity['entity_id']])) {
                $entity[$entityParentList[$entity['entity_id']]['module_code']] = $entityParentList[$entity['entity_id']];
            }

            if (!empty($task['json'])) {
                $taskJson = json_decode($task['json'], true);
                $isDismantleTask = $taskJson['is_dismantle_task'] ?? null;
                $dismantleName = $taskJson['dismantle_name'] ?? '';
            }

            $entity = array_merge($entity, $entityJson);
            unset($entity['json']);
            unset($task['json']);
            $entity['module_code'] = $taskItem['module']['code'];
            $entity['episode'] = $episodeList[$entity['initial_episode_code']] ?? null;
            $task['episode_id'] = $entity['episode']['id'] ?? 0;
            $task['executor_info'] = null;
            $task['is_outside'] = false;
            if ($task['executor_tenant_id'] > 0 && $task['executor_tenant_id'] != $currentTenantId) {
                $task['executor_info'] = $supplierRes['outside'][$task['executor_tenant_id']] ?? null;
                $task['is_outside'] = true;
            } else if ($task['department_id'] > 0) {
                $task['executor_info'] = $supplierRes['department'][$task['department_id']] ?? null;
            }
            $task['executor_user_info'] = $userDict[$task['executor']] ?? [];
            $task['task_status'] = $statusList[$task['task_status']] ?? null;
            $task['entity_name'] = $entity['name'];
            $task['entity'] = $entity;
            $task['is_dismantle_task'] = $isDismantleTask;
            $task['dismantle_name'] = $dismantleName;
            $res [] = $task;
        }

        return $res;
    }
}
